﻿using UnityEngine;
using UnityEngine.UI;
using System.Collections;

namespace BToolkit
{
    public class DrawCamera : MonoBehaviour
    {
        public bool autoStart = true;
        public RawImage image;
        public int textureSize = 1280;
        public int fps = 30;
        public WebCamTexture cameraTexture { get; private set; }
        Texture imageDefaultTexture;
        Color imageDefaultColor = Color.white;

        void Start()
        {
            image.rectTransform.sizeDelta = new Vector2(image.rectTransform.sizeDelta.x, image.rectTransform.sizeDelta.x * 3 / 4f);
            //自动启动
            if (autoStart)
            {
                StartCamera();
            }
        }

        public void StartCamera()
        {
            if (!cameraTexture)
            {
                StartCoroutine(StartCameraIEnumerator());
            }
        }

        public void StopCamera(bool clearPhoto)
        {
            if (cameraTexture)
            {
                cameraTexture.Stop();
                cameraTexture = null;
                if (clearPhoto)
                {
                    image.texture = imageDefaultTexture;
                    image.color = imageDefaultColor;
                }
            }
        }

        public bool IsPlaying
        {
            get
            {
                return cameraTexture != null;
            }
        }

        IEnumerator StartCameraIEnumerator()
        {
            yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
            if (!Application.HasUserAuthorization(UserAuthorization.WebCam))
            {
                Debug.LogError("摄影机权限被禁用");
            }
            else
            {
                WebCamDevice[] devices = WebCamTexture.devices;
                if (devices.Length > 0)
                {
                    cameraTexture = new WebCamTexture(devices[0].name, textureSize, textureSize, fps);
                }
                else
                {
                    cameraTexture = new WebCamTexture(textureSize, textureSize, fps);
                }
                cameraTexture.Play();
                imageDefaultTexture = image.texture;
                imageDefaultColor = image.color;
                image.color = Color.white;
                image.texture = cameraTexture;
                Debug.Log("CameraTexture播放成功");
            }
        }
    }
}